﻿using Stardust.Common;
using Stardust.Common.Model;
using Stardust.Common.Utils;
using System.Collections.Generic;
using System.Timers;

namespace Stardust.Server
{
    public class StardustServer
    {
        public static string ConfigCenterUrl { private set; get; }

        public static ServerNodeModel Node { get; private set; }

        public static string UniqueNodeName
        {
            get
            {
                if (Node == null) return string.Empty;
                return Node.Platform + "," + Node.ServiceName + "," + Node.Version + "," + Node.Address;
            }
        }

        private static Timer timerHeartbeat;


        #region ConfigCenterPaths
        static string GetRegisterUrl()
        {
            return ConfigCenterUrl + "/StardustConfigCenter/Register";
        }
        static string GetHeartbeatUrl()
        {
            return ConfigCenterUrl + "/StardustConfigCenter/Heartbeat";
        }
        static string GetLogoutUrl()
        {
            return ConfigCenterUrl + "/StardustConfigCenter/Logout";
        }
        static string GetUploadContractUrl()
        {
            return ConfigCenterUrl + "/StardustConfigCenter/UploadContract";
        }
        #endregion

        /// <summary>
        /// 服务跟路径 /stardust 或 /{subweb}/stardust
        /// </summary>
        public static string StardustRoot { get; private set; }


        public static bool Register(string configCenterUrl, string serviceName, string address, string version, string serviceRoot = "")
        {
            ConfigCenterUrl = configCenterUrl;

            Node = new ServerNodeModel();
            Node.ServiceName = serviceName;
            Node.Version = version;
            Node.Platform = ".NET";
            if (string.IsNullOrEmpty(serviceRoot))
            {
                StardustRoot = "/stardust";
                Node.Address = address;
            }
            else
            {
                StardustRoot = "/" + serviceRoot + "/stardust";
                Node.Address = address + "/" + serviceRoot;
            }

            var json = HttpHelper.PostJsonToUrl(GetRegisterUrl(), Node);
            var mr = SerializerHelper.DeserializeFromString<MessageResult<ServerNodeModel>>(json);
            if (mr.Success)
            {
                Node = mr.Data;
                timerHeartbeat = new Timer(5000);
                timerHeartbeat.Elapsed += TimerHeartbeat_Elapsed;
                timerHeartbeat.Start();//开始心跳
                var contractList = ActionManager.LoadActions(mr.Data); //加载服务方法,生产契约
                UploadContract(contractList);
            }
            return mr.Success;
        }

        private static void UploadContract(List<ServiceContractModel> contractList)
        {
            HttpHelper.PostJsonToUrlAsync(GetUploadContractUrl(), contractList);
        }

        private static void TimerHeartbeat_Elapsed(object sender, ElapsedEventArgs e)
        {
            var json = "{\"nodeId\":" + Node.Id + "}";
            HttpHelper.PostJsonToUrlAsync(GetHeartbeatUrl(), json);
        }

        /// <summary>
        /// 断开服务
        /// </summary>
        public static void Logout()
        {
            LogoutParams ps = new LogoutParams { NodeId = Node.Id, ServiceName = Node.ServiceName };
            HttpHelper.PostJsonToUrl(GetLogoutUrl(), ps);
        }
    }
}
